<?php

namespace App\Api\Sms;

use Illuminate\Support\Facades\Http;

class Feige extends Base
{
    protected $values = array();
//    签名
    const SignName = "5G号卡网";
    const SignId = "203636";
    private $smsType = 2;
    private $config = [
//    根据'smsType' => [0 => '验证码', 1 => '通知', 2 => '营销'],分开配置
//    通知/验证码短信
        1 => [
            "apikey" => "N11392495e0",
            "secret" => "113924c93a21fa22c"
        ],
//    营销
        2 => [
            "apikey" => "M113924810f",
            "secret" => "1139240e3262f2192"
        ]
    ];

    public function __construct($smsType = 3)
    {
        $this->smsType = $this->getNowApiType($smsType);
//        $this->root = new Logger('FeigeSmsLog');
//        $this->root->pushHandler(
//            (new RotatingFileHandler(storage_path('/logs/FeigeSmsLog.log'), 7, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
//        );
    }

    //转换平台的类型到此接口的类型
    private function getNowApiType($tplType = 3)
    {
        //0 验证码 1 通知 2 营销
        if ($tplType == 3) {
            return 2;
        } else {
            return 1;
        }
    }

//通过已经审核好的模板发送，成功率高，速度快
    public function sendSmsByTpl($phone, $tplId, $tplType = 3, $tplContent = "", $tplParamsData = [])
    {
//        分析变量
        $tplParams = $this->parseTplParams($tplContent, $tplParamsData);
        $apiUrl = 'https://api.4321.sh/sms/template';
        if (empty($phone)) {
            return $this->returnMsg(1, '发送的手机号不能为空');
        }
        if (empty($tplId)) {
            return $this->returnMsg(2, '请正确填写已经审核通过的模板');
        }
        $this->smsType = $this->getNowApiType($tplType);
        if (is_array($phone)) {
            $phone = implode(',', $phone);
        }
        $paramsContent = "";
        if (!empty($tplParams)) {
            if (is_array($tplParams)) {
                $paramsContent = implode('||', $tplParams);
            } else if (is_string($tplParams)) {
                $paramsContent = trim($tplParams);
            }
        }
        $this->values['sign_id'] = self::SignId;
        $this->values['mobile'] = $phone;
        $this->values['template_id'] = $tplId;
        $this->values['content'] = $paramsContent;
        $res = $this->requestSms($apiUrl);
//        return $this->returnMsg(15, 'f发送', $res);
//        print_r($res);
        if (intval($res['code']) === 0) {
            $data = [
                'smsId' => $res['msg_no']
            ];
            return ['code' => 200, 'msg' => '发送成功', 'data' => $data];
        }
        return ['code' => -1, 'msg' => $res['msg']];
    }

//发送短信,通过内容发送，这个可能会收不到，内容都要审核
    public function sendSms($phone, $content, $smsType = 3)
    {
        $apiUrl = 'https://api.4321.sh/sms/send';
        if (empty($phone)) {
            return $this->returnMsg(1, '发送的手机号不能为空');
        }
        $this->smsType = $this->getNowApiType($smsType);
        if (is_array($phone)) {
            $phone = implode(',', $phone);
        }
        $this->values['sign_id'] = self::SignId;
        $this->values['mobile'] = $phone;
        $this->values['content'] = $content;
        $res = $this->requestSms($apiUrl);
        if (intval($res['code']) === 0) {
            $data = [
                'smsId' => $res['msg_no']
            ];
            return ['code' => 200, 'msg' => '发送成功', 'data' => $data];
        }
        return ['code' => -1, 'msg' => $res['msg']];
    }


//创建短信模版
    public function addTpl($tplName, $tplType, $tplContent)
    {
        if (empty($tplName) || empty($tplContent)) {
            return ['code' => -1, 'msg' => '模版内容缺少必要内容'];
        }
//        模板内容，营销短信，请带 退订回T（加上短信签名，不超过350个字符）
        $tplContent = preg_replace("/【.+?】/", '', $tplContent);
        //把自己的变量转为平台的变量格式
        $tplContent = preg_replace("/\{%(.+?)%}/", '$$', $tplContent);

//        if ($tplType == 3) {
////            短信模板类型 1、验证码，2、通知，3、营销
////            $tplContent = $tplContent . "拒收回R";
//            $this->smsType = 3;
//        }
        $this->smsType = $this->getNowApiType($tplType);
        $apiUrl = 'https://api.4321.sh/smstemplate/insert';
        $this->values['type'] = $this->smsType;
        $this->values['name'] = $tplName;
        $this->values['template'] = $tplContent;
        $res = $this->requestSms($apiUrl);
//        print_r($res);
        if (intval($res['code']) === 0) {
            $data = [
                'templateId' => $res['id']
            ];
            return ['code' => 200, 'msg' => '创建模版成功', 'data' => $data];
        }
        return ['code' => -1, 'msg' => $res['msg']];
    }

//    修改模版内容
    public function editTpl($tplId, $tplType, $tplName, $tplContent)
    {
//        if ($tplType == 3) {
////            短信模板类型 1、验证码，2、通知，3、营销
////            $tplContent = $tplContent . "拒收回R";
//        }
        $this->smsType = $this->getNowApiType($tplType);
        //把自己的变量转为平台的变量格式
        $tplContent = preg_replace("/\{%(.+?)%}/", '$$', $tplContent);

        $apiUrl = 'https://api.4321.sh/smstemplate/update';
        $this->values['id'] = $tplId;
        $this->values['name'] = $tplName;
        $this->values['template'] = $tplContent;
        $this->values['type'] = $this->smsType;
        $res = $this->requestSms($apiUrl);
//        print_r($res);
        if (intval($res['code']) === 0) {
            return ['code' => 200, 'msg' => '修改模版成功', 'data' => $res];
        }
        return ['code' => -1, 'msg' => $res['msg']];
    }

//    删除模版
    public function delTpl($tpl_id, $tplType = 3)
    {
        $this->smsType = $this->getNowApiType($tplType);
        $apiUrl = 'https://api.4321.sh/smstemplate/delete';
        $this->values['id'] = $tpl_id;
        $res = $this->requestSms($apiUrl);
//        print_r($res);
        if (intval($res['code']) === 0) {
            return ['code' => 200, 'msg' => '删除模版成功', 'data' => $res];
        }
        return ['code' => -1, 'msg' => '删除模版失败', $res];
    }

//短信查询模板
    public function queryTpl($tpl_id = null, $tplType = 3)
    {
        if (empty($tpl_id)) {
            return ['code' => -1, 'msg' => '查询模版不能为空'];
        }
        $this->smsType = $this->getNowApiType($tplType);
        $apiUrl = 'https://api.4321.sh/smstemplate/detail';
        $this->values['id'] = $tpl_id;
        $res = $this->requestSms($apiUrl);
        if (intval($res['code']) === 0) {
//            统一的数据
            $data = [
                'verifyStatus' => $res['data']['status'],
            ];
            return ['code' => 200, 'msg' => '查询模版成功', 'data' => $data];
        }
        return ['code' => -1, 'msg' => $res['msg']];
    }

//    短信余额查询
    public function getBalance()
    {
        $apiUrl = 'https://api.4321.sh/balance/balance';
        $res = $this->requestSms($apiUrl);
//        print_r($res);
        if (intval($res['code']) === 0) {
            $data = [
                'balance' => $res['balance']
            ];
            return ['code' => 200, 'msg' => '修改模版成功', 'data' => $data];
        }
        return ['code' => -1, 'msg' => $res['msg']];
    }

    protected function requestSms($apiUrl)
    {
        $this->values['apikey'] = $this->config[$this->smsType]['apikey'] ?? '';
        $this->values['secret'] = $this->config[$this->smsType]['secret'] ?? '';
//        print_r($this->values);
        $response = Http::withOptions([
//            'debug' => false,
            'timeout' => 30,
            'connect_timeout' => 30,
            'read_timeout' => 30
        ])->withHeaders([
            'Accept' => 'application/json',
            'Content-Type' => 'application/json;charset=utf-8'
        ])->post($apiUrl, $this->values);
        return $response->json();
    }
}
